# -*- coding: utf-8 -*-

# manual_server.py
import http.server
import socketserver
import webbrowser
import threading
import time

# 创建HTML内容
html_content = """
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>测试服务器</title>
    <style>
        body { font-family: Arial, sans-serif; padding: 50px; text-align: center; }
        .success { color: green; font-size: 24px; }
    </style>
</head>
<body>
    <h1>🎉 服务器工作正常！</h1>
    <p class="success">如果你看到这个页面，说明Python和浏览器之间的连接正常</p>
    <p>现在可以尝试运行Streamlit了</p>
</body>
</html>
"""

# 保存HTML文件
with open("test.html", "w", encoding="utf-8") as f:
    f.write(html_content)

class MyHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
    def do_GET(self):
        if self.path == "/" or self.path == "/index.html":
            self.send_response(200)
            self.send_header('Content-type', 'text/html; charset=utf-8')
            self.end_headers()
            self.wfile.write(html_content.encode('utf-8'))
        else:
            super().do_GET()

def start_server():
    PORT = 8000
    with socketserver.TCPServer(("", PORT), MyHTTPRequestHandler) as httpd:
        print(f"✅ 测试服务器启动成功！")
        print(f"📱 请访问: http://localhost:{PORT}")
        
        # 自动打开浏览器
        def open_browser():
            time.sleep(1)
            webbrowser.open(f'http://localhost:{PORT}')
        
        threading.Thread(target=open_browser, daemon=True).start()
        httpd.serve_forever()

if __name__ == "__main__":
    print("🚀 启动测试服务器...")
    try:
        start_server()
    except KeyboardInterrupt:
        print("\n👋 服务器已停止")